import React, { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { useAtomValue } from 'jotai'
import { currentChatAtom } from '@/atoms'
import { ChatOptions } from '@/types'
import { useTranslation } from 'react-i18next'
import useChat from '@/hooks/useChat'
import {
  Button, Box,
  Dialog, DialogContent, DialogActions, DialogTitle,
  FormControl, Switch, FormControlLabel, FormLabel,
  TextField, Slider, RadioGroup, Radio,
} from '@mui/material'

let externalSetDialogOptions: (state: boolean) => void = () => {}

const EditChatDialog: React.FC = () => {
  const { t } = useTranslation()
  const [open, setOpen] = useState(false)
  const currentChat = useAtomValue(currentChatAtom)
  const [values, setValues] = useState<ChatOptions>()
  const { modifyChatInfo } = useChat()

  useEffect(() => {
    externalSetDialogOptions = setOpen
  }, [])

  useEffect(() => {
    if (currentChat) {
      setValues(currentChat.options)
    }
  }, [open])

  const onCancel = () => {
    setOpen(false)
  }
  const onSave = () => {
    if (values && currentChat) {
      modifyChatInfo({ ...currentChat, options: values })
    }
    onCancel()
  }

  if (!open || !values) return null

  return createPortal(
    <Dialog
      open
      onClose={onCancel}
      fullWidth
    >
      <DialogTitle>{t('Chat Settings')}</DialogTitle>
      <DialogContent>
        <Box>
          <FormControl>
            <FormLabel>reasoning_effort</FormLabel>
            <RadioGroup
              value={values.reasoning_effort}
              onChange={e => setValues({ ...values, reasoning_effort: e.target.value })}
              row
            >
              <FormControlLabel value="low" control={<Radio />} label="low" />
              <FormControlLabel value="medium" control={<Radio />} label="medium" />
              <FormControlLabel value="high" control={<Radio />} label="high" />
            </RadioGroup>
          </FormControl>
        </Box>
        <Box>
          <FormControl fullWidth>
            <FormLabel>frequency_penalty</FormLabel>
            <Box className="w-full flex">
              <Box className="mr-1rem flex-1">
                <Slider
                  value={values.frequency_penalty}
                  min={-2.0}
                  max={2.0}
                  step={0.1}
                  marks={[{ label: -2.0, value: -2.0 }, { label: 2.0, value: 2.0 }]}
                  onChange={(_, nv) => setValues({ ...values, frequency_penalty: nv as number })}
                />
              </Box>
              <TextField
                className="w-5rem"
                value={values.frequency_penalty}
                onChange={event => setValues({ ...values, frequency_penalty: Number(event.target.value) })}
                type="number"
                size="small"
                slotProps={{ htmlInput: { step: 0.1 } }}
                variant="outlined"
              />
            </Box>
          </FormControl>
        </Box>
        <Box>
          <FormControl fullWidth>
            <FormLabel>presence_penalty</FormLabel>
            <Box className="w-full flex">
              <Box className="mr-1rem flex-1">
                <Slider
                  value={values.presence_penalty}
                  min={-2.0}
                  max={2.0}
                  step={0.1}
                  marks={[{ label: -2.0, value: -2.0 }, { label: 2.0, value: 2.0 }]}
                  onChange={(_, nv) => setValues({ ...values, presence_penalty: nv as number })}
                />
              </Box>
              <TextField
                className="w-5rem"
                value={values.presence_penalty}
                onChange={event => setValues({ ...values, presence_penalty: Number(event.target.value) })}
                type="number"
                size="small"
                slotProps={{ htmlInput: { step: 0.1 } }}
                variant="outlined"
              />
            </Box>
          </FormControl>
        </Box>
        <Box>
          <FormControl fullWidth>
            <FormLabel>temperature</FormLabel>
            <Box className="w-full flex">
              <Box className="mr-1rem flex-1">
                <Slider
                  value={values.temperature}
                  min={0}
                  max={2.0}
                  step={0.1}
                  marks={[{ label: 0, value: 0 }, { label: 2.0, value: 2.0 }]}
                  onChange={(_, nv) => setValues({ ...values, temperature: nv as number })}
                />
              </Box>
              <TextField
                className="w-5rem"
                value={values.temperature}
                onChange={event => setValues({ ...values, temperature: Number(event.target.value) })}
                type="number"
                size="small"
                slotProps={{ htmlInput: { step: 0.1 } }}
                variant="outlined"
              />
            </Box>
          </FormControl>
        </Box>
        <Box className="flex items-center justify-start">
          <FormLabel>max_completion_tokens</FormLabel>
          <Switch
            checked={values.max_tokens_limit}
            onChange={(_, checked) => setValues({ ...values, max_tokens_limit: checked })}
          />
          {
            values.max_tokens_limit
              ? (
                  <TextField
                    value={values.max_completion_tokens}
                    size="small"
                    type="number"
                    onChange={e => setValues({ ...values, max_completion_tokens: e.target.value })}
                  />
                )
              : null
          }
        </Box>
        <Box>
          <FormControl>
            <FormLabel>n</FormLabel>
            <RadioGroup
              value={values.n}
              onChange={e => setValues({ ...values, n: Number(e.target.value) })}
              row
            >
              <FormControlLabel value={1} control={<Radio />} label="1" />
              <FormControlLabel value={2} control={<Radio />} label="2" />
              <FormControlLabel value={3} control={<Radio />} label="3" />
            </RadioGroup>
          </FormControl>

        </Box>
        <Box className="flex justify-end">
          <FormControl>
            <FormControlLabel
              control={<Switch />}
              label="store"
              labelPlacement="start"
              checked={values.store}
              onChange={(_, checked) => setValues({ ...values, store: checked })}
            />
          </FormControl>
          <FormControlLabel
            control={<Switch />}
            label="logprobs"
            labelPlacement="start"
            checked={values.logprobs}
            onChange={(_, checked) => setValues({ ...values, logprobs: checked })}
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onCancel}>{t('dialog cancel btn')}</Button>
        <Button onClick={onSave}>{t('dialog ok btn')}</Button>
      </DialogActions>
    </Dialog>,
    document.body,
  )
}

export const showEditChatDialog = () => {
  externalSetDialogOptions(true)
}

export const hideEditChatDialog = () => {
  externalSetDialogOptions(false)
}

export default EditChatDialog
